package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.SendSms;
import com.itheima.reggie.dto.LoginDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;


    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpServletRequest request){
        //1.生成一个验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        System.out.println("生成验证码为"+code);
        //2.发送给指定的手机
        //SendSms.sendMsg(user.getPhone(),code+"");
        //3.把验证码存储到se'e'si'o'n中等待后续的验证码的校验
        HttpSession session = request.getSession();
        session.setAttribute(user.getPhone(),code+"");
        return R.success("发送验证码成功");
    }


    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto,HttpServletRequest request){

        //1). 获取前端传递的手机号和验证码
        if(null == loginDto){
            return R.error("参数异常");
        }
        //2). 从Session中获取到手机号对应的正确的验证码
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute(loginDto.getPhone());
        //2.1 校验一下code 如果为空
        if(null == code || code == ""){
            return R.error("请先获得验证码..");
        }

        //3). 进行验证码的比对 , 如果比对失败, 直接返回错误信息
        if(!code.equals(loginDto.getCode())){//代表验证码相等
            return R.error("验证码不匹配");
        }
        //4). 如果比对成功, 需要根据手机号查询当前用户, 如果用户不存在, 则自动注册一个新用户
        LambdaQueryWrapper<User> wapper = new LambdaQueryWrapper<>();
        wapper.eq(User::getPhone,loginDto.getPhone());
        User user = userService.getOne(wapper);
        if(user == null){ //代表用户不存在
            //注册一个用户
            user = new User();
            user.setPhone(loginDto.getPhone());
            //4.1 插入数据库中
            userService.save(user);
        }
        //5). 将登录用户的ID存储Session中
        session.setAttribute("user",user.getId());

        return R.success("登录成功");
    }
}